"""Rule engine and state machine (skeleton)."""
from __future__ import annotations
from dataclasses import dataclass


@dataclass
class ViolationState:
    person_in_roi_frames: int = 0
    vehicle_near_frames: int = 0
    candidate_frames: int = 0
    cooldown_frames_left: int = 0


def update_state(persons_in_roi: bool, vehicle_near: bool, vs: ViolationState, cfg: dict):
    def inc_or_reset(v, cond):
        return v + 1 if cond else 0

    vs.person_in_roi_frames = inc_or_reset(vs.person_in_roi_frames, persons_in_roi)
    vs.vehicle_near_frames = inc_or_reset(vs.vehicle_near_frames, vehicle_near)

    if vs.cooldown_frames_left > 0:
        vs.cooldown_frames_left -= 1
        return None, "Cooldown"

    if vs.person_in_roi_frames >= cfg.get("N_person", 2) and vs.vehicle_near_frames >= cfg.get("N_vehicle", 2):
        vs.candidate_frames += 1
        if vs.candidate_frames >= cfg.get("FRAMES_NEED", 6):
            vs.cooldown_frames_left = cfg.get("COOLDOWN", 30)
            return {"type": "no_yield"}, "Alarming"
    else:
        vs.candidate_frames = 0
    return None, "Monitoring"

